package com.yobol.jgrowth.controller;

import com.yobol.jgrowth.domain.Article;
import com.yobol.jgrowth.domain.ArticleComment;
import com.yobol.jgrowth.service.ArticleCommentService;
import com.yobol.jgrowth.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Manage article comment request
 *
 * @author yobol
 * @create 2018-04-05 20:21
 **/

@Controller
public class ArticleCommentController {

    @Autowired
    private ArticleService articleService;
    @Autowired
    private ArticleCommentService articleCommentService;

    @RequestMapping(value = "create_article_comment",method = {RequestMethod.POST,RequestMethod.GET})
    public String createArticleComment(HttpServletRequest request, HttpServletResponse response){
        int uid = (Integer)request.getSession().getAttribute("uid");
        String username = (String)request.getSession().getAttribute("username");
        int aid = Integer.parseInt(request.getParameter("aid"));
        ArticleComment comment = new ArticleComment();
        comment.setContent(request.getParameter("comment"));
        comment.setUid(uid);
        comment.setUsername(username);
        comment.setAid(aid);
        articleCommentService.insert(comment);
        Article article = articleService.getArticleByAid(aid);
        Article newArticle = new Article();
        newArticle.setAid(aid);
        newArticle.setCommentedCtr(article.getCommentedCtr() + 1);
        articleService.updateArticleCommentedCtr(newArticle);
        request.getSession().setAttribute("article",article);
        request.getSession().setAttribute("comments",articleCommentService.getArticleCommentsByAid(aid));
        return "redirect:/article";
    }
}
